package com.cherry.sdk.http.exception

import com.google.gson.JsonParseException
import retrofit2.HttpException
import java.io.EOFException
import java.net.ProtocolException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.*

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-14
 */

object ExceptionParser {


    fun parse(error: Throwable): NetworkException {
        return onParse(error)
    }


    private fun onParse(ioe: Throwable): NetworkException {
        if (ioe is JsonParseException) {
            return NetworkException.EXCEPTION_APP_INTERNAL_ERROR
        }

        val msg = ioe.message.toString().toUpperCase(Locale.US)
        if (msg.contains("CANCEL") || msg.contains("SOCKET CLOSED") || msg.contains("SOCKET IS CLOSED")) {
            //不需要提示的异常，如客户端取消请求
            return NetworkException.EXCEPTION_QUIET
        }
        if (ioe is HttpException) {
            if (ioe.code() >= 500) {
                // 服务端错误按超时提示
                return NetworkException.EXCEPTION_TIMEOUT
            }
        }
        if (msg.contains("ECONNREFUSED") || msg.contains("FAILED TO CONNECT")
                || ioe is UnknownHostException
                || msg.contains("ENETUNREACH") || msg.contains("EHOSTUNREACH")
                || msg.contains("ECONNRESET") || msg.contains("EAI_NODATA")
                || ioe is EOFException || ioe is ProtocolException
                || ioe is SocketException
                || msg.contains("EPIPE") || msg.contains("EINVAL")) {
            /*Network is unreachable*/
            return NetworkException.EXCEPTION_NETWORK_UNREACHABLE
        }
        if (ioe is SocketTimeoutException || msg.contains("TIMEOUT")
                || msg.contains("ETIMEDOUT")) {
            return NetworkException.EXCEPTION_TIMEOUT
        }
        return if (msg.contains("PERMISSION DENIED")) NetworkException.EXCEPTION_PERMISSION_DENIED else NetworkException.EXCEPTION_UNHANDLED
    }
}